package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;


    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list = getDateList(begin, end);

        //2.准备营业额数据
        //查询order表，条件： 状态--已完成 下单时间
        //select sum(amount) from orders where status = 5 and order_time between '2024-05-14 00:00:00' and '2024-05-14 23:59:59'
        List<Double> turnoverList = new ArrayList<>();
        list.forEach(date -> {
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));  //2024-05-14 00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));  //2024-05-14 23:59:59
            Double sum = ordersMapper.sumByMap(map);
            //营业额为null，则设置0.0，处理没有营业额的情况
            sum = sum == null ? 0.0: sum;
            turnoverList.add(sum);
        });

        //3.组装TurnoverReportVO返回结果

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(list,","))   //2024-05-14,2024-05-15,2024-05-16,把里面的日期用逗号拼接，并去掉[]
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.构造datelist数据
        List<LocalDate> dateList = getDateList(begin, end);

        //2.构造newuserlist数据（新增用户数）
        List<Integer> newUserList = new ArrayList<>();
        //3.构造totaluserlist数据
        List<Integer> totalUserList = new ArrayList<>();


        Map map = new HashMap();
        //循环遍历dateList集合
        dateList.forEach(date -> {
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
            log.info("newUser = {}",newUser);

            //（当天总用户数：等于这一天之前的所有用户）复用一个countByMap方法
            map.put("beginTime",null);
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            log.info("totalUser = {}",totalUser);
        });

        //4.组装UserReportVO返回结果
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.构造日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        //2.有效订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();
        //3.订单数列表
        List<Integer> orderCountList = new ArrayList<>();
        //4.总订单数列表
        Integer totalOrder = 0;
        //5.有效订单数
        Integer validOrder = 0;


        //2.有效订单数列表
        //select count(*) from orders where status = 5 and order_time between #{} and #{}

        for (LocalDate date : dateList) {
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN));
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX));
            Integer list = ordersMapper.ordersStatistics(map);    //获取每日有效订单数
            validOrderCountList.add(list);                       //添加到validOrderCountList

            //3.订单数列表
            //select count(*) from orders where order_time between #{} and #{}
            map.put("status", null);
            Integer list2 = ordersMapper.ordersStatistics(map);  //获取每日订单数
            orderCountList.add(list2);                          //添加到orderCountList

            //4.总订单数
            totalOrder+= list2;

            //5.有效订单数
            validOrder+= list;
        }

        //6.计算订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrder != 0){
            orderCompletionRate = validOrder * 1.0 / totalOrder;
        }


        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))   //日期列表
                .orderCountList(StringUtils.join(orderCountList,","))   //订单数列表
                .validOrderCountList(StringUtils.join(validOrderCountList,","))   //有效订单数列表
                .validOrderCount(validOrder)   //有效订单数
                .totalOrderCount(totalOrder)   //订单总数
                .orderCompletionRate(orderCompletionRate)
                .build();

        log.info("订单统计vo = {}",vo);
        return vo;
    }


    /**
     * 销量排名
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1.构造名称列表
        List<String> nameList = new ArrayList<>();
        //2.构造销量列表
        List<Integer> numberList = new ArrayList<>();

        Map map = new HashMap();
        map.put("status", Orders.COMPLETED);
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
        List<GoodsSalesDTO> list = ordersMapper.sumTop10(map);

        for (GoodsSalesDTO dto : list) {
            nameList.add(dto.getName());
            numberList.add(dto.getNumber());
        }

        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
        log.info("销量排名vo = {}",vo);
        return vo;
    }


    /**
     *
     * 抽取公共方法,获取日期列表数据
     * @param begin
     * @param end
     * @return
     */
    public List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> list = new ArrayList<>();
        //循环加入日期
        while (!begin.isAfter(end)){
            list.add(begin);
            begin = begin.plusDays(1);
        }
        log.info("list = {}，",list);
        return list;
    }

}
